from appserver import db_store
from sqlalchemy.sql import func
from sqlalchemy import or_

# from models.entity.device import Device
from models.entity.district_item import DistrictItem
from models.entity.district_with_device import DistrictWithDevice
from models.entity.district_with_facility import DistrictWithFacility
from models.entity.facility import Facility
from models.entity.tree_model_base import TreeModelBase
# 主分区，行政区

class  District(TreeModelBase):
    __tablename__ = "district"
    __bind_key__ = "main"

    # autoincrement=True,
    # id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    name = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'名称')
    code = db_store.Column(db_store.String(32), nullable=False, unique=True, comment=u"编码")
    description = db_store.Column(db_store.String(255), comment=u"描述")
    dis_order = db_store.Column(db_store.Integer, comment=u"排序",default=0)
    status = db_store.Column(db_store.Integer, comment=u"状态",default = 0)  # 0-正常 1-未开启 2-弃用
    points = db_store.relationship('DistrictItem', backref='district_item', lazy='dynamic') # 表里不创建字段
    parent_id = db_store.Column(db_store.Integer, comment=u"状态", default=0)  #父id  0表示自己是最顶层
    lat = db_store.Column(db_store.Float,nullable=False)
    lng = db_store.Column(db_store.Float,nullable =False)
    # path =db_store.Column(db_store.String(32), nullable=False, unique=False, comment=u"lujing")
    # path = db_store.Column(db_store.String(32), nullable=True, comment=u"lujing")
    depth = db_store.Column(db_store.Integer, default=1)

    def __repr__(self):
        return "<District_item %s>" % self.name

    def to_dict(self):
        rdic={}
        rdic["data_type"]=1
        rdic["id"]=self.id
        rdic["name"]=self.name
        rdic["code"]=self.code
        rdic["description"]=self.description
        rdic["dis_order"]=self.dis_order
        rdic["status"]=self.status
        rdic["item"]=[]
        for item in self.points:
            rdic["item"].append(item.get_dic())
        rdic["lat"]=self.lat
        rdic["lng"]=self.lng
        rdic["path"]=self.path
        rdic["parent_id"]=self.parent_id
        rdic["level"]=self.depth
        return rdic

    @staticmethod
    def get_district_all():
        return District.query.order_by("dis_order").all()

    @staticmethod
    def get_district_by_id(id_num):
        return District.query.filter_by(id=id_num).first()

    @staticmethod
    def get_district_by_name(name):
        return District.query.filter_by(name=name).first()

    @staticmethod
    def get_district_by_code(code):
        return District.query.filter_by(code=code).first()

    @staticmethod
    def get_points_by_district_id(district_id):
        district=District().get_entity_by_id(district_id)
        return district.points

    @staticmethod
    def get_facilities_by_district_id(district_id):
        rlist = []
        connectors = DistrictWithFacility.query.filter_by(district_id=district_id).all()
        for item in connectors:
            t = Facility.query.filter_by(id=item.facility_id).first()
            rlist.append(t)
        return rlist
    # 不能相互导入,
    # @staticmethod
    # def get_devices_by_district_id(district_id):
    #     rlist = []
    #     connectors = DistrictWithDevice.query.filter_by(district_id=district_id).all()
    #     for item in connectors:
    #         t = Device.query.filter_by(id=item.device_id).first()
    #         rlist.append(t)
    #     return rlist

    @staticmethod
    def search(query_word):
        data = []
        buttons = District.query.filter(
            or_(District.code.like('%' + query_word + '%'), District.name.like('%' + query_word + '%'),
                District.description.like('%' + query_word + '%'))).all()
        for obj in buttons:
            tlist=[]
            for p in DistrictItem.get_district_items_by_district(obj.id):
                tlist.append(p.to_dict())
            data.append(obj.to_dict())
        #
        rdic = {
            "success": 1,
            "error_code": None,
            "error_msg": None,
            "data": data
        }
        # return (data,len('长度',data))
        return rdic

    def get_max_id(self):
        val = db_store.session.query(func.max(District.id)).scalar()
        if not val:
            return 0
        else:
            return val

    # def save(self):
    #
    #     if self.id is None:
    #         self.id = self.get_max_id() + 1
    #     try:
    #         db_store.session.add(self)
    #         db_store.session.commit()
    #         return True
    #     except Exception as e:
    #         print("error is ")
    #         print(e)
    #         db_store.session.rollback()
    #         return False

    ##应该用tree_module_base
    # def save(self):
    #     if self.id == 0:
    #         print(11,'****')
    #         self.id = self.get_max_id() + 1
    #     if District.query.filter_by(id=self.parent_id).first():
    #         print(555555)
    #         p_district = District.query.filter_by(id=self.parent_id).first()
    #         self.path = p_district.path + "," + str(self.id)
    #         self.depth = p_district.depth + 1
    #     else:
    #         print(22)
    #         self.path = str(self.id)
    #         self.depth = 1
    #     try:
    #         db_store.session.add(self)
    #         db_store.session.commit()
    #         return True
    #     except Exception as e:
    #         print(e)
    #         db_store.session.rollback()
    #         return False


